package com.ruoyi.demo;


import java.util.concurrent.*;

/**
 * @author tjw
 * @date 2024-07-13
 * @Description
 */
public class AsyncDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        futureDemo();
    }

    /**
     * 异步并行
     * @throws InterruptedException
     * @throws ExecutionException
     */
    private static void futureDemo() throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        Callable<Integer> task1 = () -> {
            Thread.sleep(2000); // 模拟耗时操作
            return 123;
        };
        Callable<String> task2 = () -> {
            Thread.sleep(3000); // 模拟耗时操作
            return "Hello";
        };
        // 提交并执行任务
        Future<Integer> future1 = executor.submit(task1);
        Future<String> future2 = executor.submit(task2);
        // 异步执行其他任务，比如打印日志或处理其他请求
        System.out.println("Doing other work while tasks are executed in parallel...");
        // 获取任务结果
        Integer result1 = future1.get(); // 会阻塞直到task1完成
        String result2 = future2.get(); // 会阻塞直到task2完成
        System.out.println("Result 1: " + result1);
        System.out.println("Result 2: " + result2);
        // 关闭ExecutorService
        executor.shutdown();
    }
}
